/**
 * Created by xxcao on 2017/6/14.
 */


var sql = require('./sqlMapping');
var util = require('../util/util');
var code = require('../util/code');

module.exports = {
     create:function (req, res, next) {
         if (util.isParameterEmpty(req.body.user_id, req.body.task_id, req.body.issue_content)){
             res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
             return;
         }
         if (!util.isValidSession(req, 'POST')) {
             res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
             return;
         }
         mysqlPool.connection(function (err, connection) {
             if (err){
                 throw err;
             }
             new Promise(function (resolve) {
                 connection.query(sql.issue.findOne, [req.body.task_id, req.body.issue_content], function (err, result) {
                     if (err) {
                         res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '创建问题失败'));
                         connection.release();
                     } else {
                         if(result.length > 0) {
                             res.json(util.toJson(code.EXISTED, '该任务下存在相同名称的问题，请重试'));
                             connection.release();
                         } else {
                             resolve(result);
                         }
                     }
                 });
             })
                 .then(function (result) {
                 return new Promise(function (resolve) {
                     var issue_id = util.getUUID();
                     var issue_remark = null;
                     if (!util.isParameterEmpty(req.body.issue_remark)) {
                         issue_remark = req.body.issue_remark;
                     }
                     var params = [issue_id, req.body.task_id, req.body.issue_content, issue_remark, req.body.user_id];
                     connection.query(sql.issue.insert, params, function (err, result) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '创建问题失败'));
                             connection.release();
                         } else {
                             resolve(result)
                         }
                     });
                 });
             })
                 .then(function (result) {
                 return new Promise(function (resolve) {
                     connection.query(sql.task.findOne, [req.body.task_id], function (err, result) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '创建问题失败'));
                             connection.release();
                         } else {
                             resolve(result[0]);
                         }
                     });
                 });
             })
                 .then(function (result) {
                 return new Promise(function (resolve) {
                     var task = result;
                     var count = Number(task.issue_count);
                     count++;
                     connection.query(sql.issue.updateOne, [count, req.body.task_id], function (err, result) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '创建问题失败'));
                             connection.release();
                         } else {
                             res.json(util.toJson(code.OPERATE_SUCCESS, '创建问题成功'));
                             // connection.release();
                             resolve(task);
                         }
                     });
                 });
             })
                 .then(function (result) {
                 return new Promise(function (resolve) {
                     var task = result;
                     connection.query(sql.board.findBoardMembersAll, [task.board_id], function (err, results) {
                         if (err) {
                             connection.release();
                         } else {
                             if(results.length > 0) {
                                 var index = 0;
                                 //查找当前操作者
                                 for (var i = 0; i < results.length; i++){
                                     if (results[i].user_id === req.body.user_id){
                                         index = i;
                                         break;
                                     }
                                 }
                                 var content = results[index].user_name + '给任务：' + task.task_content + '创建了一个问题';
                                 var params = [];
                                 var sqls = [];
                                 for (var j = 0; j < results.length; j++) {
                                     if (results[j].user_id !== req.body.user_id) {
                                         if (!util.isParameterEmpty(results[j].client_id)) {
                                             getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                 console.log(data);
                                             },function (err) {
                                                 console.error(err);
                                             });
                                         }
                                     }
                                     //插入动态消息
                                     sqls.push(sql.news.insert);
                                     params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                 }
                                 msqlQueries.queries(sqls, params, function (err, result) {
                                     connection.release();
                                 });
                             }
                             else {
                                 connection.release();
                             }
                         }
                     });
                 });
             });
         });
     },
     delete:function (req, res, next) {
         if (util.isParameterEmpty(req.body.user_id, req.body.issue_id)){
             res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
             return;
         }
         if (!util.isValidSession(req, 'POST')) {
             res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
             return;
         }
         mysqlPool.connection(function (err, connection) {
             if (err){
                 throw err;
             }
             new Promise(function (resolve) {
                 connection.query(sql.issue.findIssue, [req.body.issue_id], function (err, result) {
                     if (err) {
                         res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '删除问题失败'));
                         connection.release();
                     } else {
                         if(result.length > 0) {
                             resolve(result[0]);
                         } else {
                             res.json(util.toJson(code.NOT_EXISTED, '没有该问题，无法删除'));
                             connection.release();
                         }
                     }
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     var issue = result;
                     connection.query(sql.issue.deleteOne, [req.body.issue_id], function (err, result) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '删除问题失败'));
                             connection.release();
                         } else {
                             resolve(issue.task_id)
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     var task_id = result;
                     connection.query(sql.task.findOne, [task_id], function (err, result) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '删除问题失败'));
                             connection.release();
                         } else {
                             resolve(result[0]);
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     var task = result;
                     var count = Number(task.issue_count);
                     count--;
                     if(count < 0) {
                         count = 0;
                     }
                     connection.query(sql.issue.updateOne, [count, task.task_id], function (err, result) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '删除问题失败'));
                             connection.release();
                         } else {
                             res.json(util.toJson(code.OPERATE_SUCCESS, '删除问题成功'));
                             // connection.release();
                             resolve(task);
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     var task = result;
                     connection.query(sql.board.findBoardMembersAll, [task.board_id], function (err, results) {
                         if (err) {
                             connection.release();
                         } else {
                             if(results.length > 0) {
                                 var index = 0;
                                 //查找当前操作者
                                 for (var i = 0; i < results.length; i++){
                                     if (results[i].user_id === req.body.user_id){
                                         index = i;
                                         break;
                                     }
                                 }
                                 var content = results[index].user_name + '删除了任务：' + task.task_content + '的一个问题';
                                 var params = [];
                                 var sqls = [];
                                 for (var j = 0; j < results.length; j++) {
                                     if (results[j].user_id !== req.body.user_id) {
                                         if (!util.isParameterEmpty(results[j].client_id)) {
                                             getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                 console.log(data);
                                             },function (err) {
                                                 console.error(err);
                                             });
                                         }
                                     }
                                     //插入动态消息
                                     sqls.push(sql.news.insert);
                                     params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                 }
                                 msqlQueries.queries(sqls, params, function (err, result) {
                                     connection.release();
                                 });
                             }
                             else {
                                 connection.release();
                             }
                         }
                     });
                 });
             });
         });
     },
     commit:function (req, res, next) {
         if (util.isParameterEmpty(req.body.user_id, req.body.issue_id)){
             res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
             return;
         }
         if (!util.isValidSession(req, 'PUT')) {
             res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
             return;
         }
         mysqlPool.connection(function (err, connection) {
             if (err) {
                 throw err;
             }
             var task = null;
             new Promise(function (resolve) {
                 connection.query(sql.issue.findIssue, [req.body.issue_id], function (err, result) {
                     if (err) {
                         res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '提交问题失败'));
                         connection.release();
                     } else {
                         if (result.length > 0){
                             resolve(result[0]);
                         } else {
                             res.json(util.toJson(code.NOT_EXISTED, '问题不存在，无法提交'));
                             connection.release();
                         }
                     }
                 });
             }).then(function (result) {
                 //判断user_id是否是任务的执行人
                 return new Promise(function (resolve) {
                     var issue = result;
                     connection.query(sql.task.findOne, [issue.task_id], function (err, results) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '提交问题失败'));
                             connection.release();
                         } else {
                             if (results.length > 0){
                                 task = results[0];
                                 if(req.body.user_id === results[0].task_executor){
                                     resolve(issue);
                                 } else if (util.isParameterEmpty(results[0].task_executor)){
                                     res.json(util.toJson(code.NOT_EXISTED, '问题所归属的任务无执行人，无法提交'));
                                     connection.release();
                                 } else {
                                     res.json(util.toJson(code.IS_NOT_TO_BE, '该用户不是任务的执行人，无法提交'));
                                     connection.release();
                                 }
                             } else {
                                 res.json(util.toJson(code.NOT_EXISTED, '问题所归属的任务不存在，无法提交'));
                                 connection.release();
                             }
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     var issue = result;
                     if (issue.current_status === 0 || issue.current_status === 3){
                         //只有状态为0（未完成）或者为3（已打回）时可以提交
                         resolve(issue);
                     } else {
                         res.json(util.toJson(code.IS_NOT_CAN, '问题的状态不对，无法提交'));
                         connection.release();
                     }
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     connection.query(sql.issue.updateStatus, [1, req.body.issue_id], function (err, result) {
                         if(err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '问题提交失败'));
                             connection.release();
                         } else {
                             res.json(util.toJson(code.OPERATE_SUCCESS, '问题提交成功'));
                             // connection.release();
                             resolve();
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     connection.query(sql.board.findBoardMembersAll, [task.board_id], function (err, results) {
                         if (err) {
                             connection.release();
                         } else {
                             if(results.length > 0) {
                                 var index = 0;
                                 //查找当前操作者
                                 for (var i = 0; i < results.length; i++){
                                     if (results[i].user_id === req.body.user_id){
                                         index = i;
                                         break;
                                     }
                                 }
                                 var content = results[index].user_name + '在任务：' + task.task_content + '里提交了一个问题';
                                 var params = [];
                                 var sqls = [];
                                 for (var j = 0; j < results.length; j++) {
                                     if (results[j].user_id !== req.body.user_id) {
                                         if (!util.isParameterEmpty(results[j].client_id)) {
                                             getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                 console.log(data);
                                             },function (err) {
                                                 console.error(err);
                                             });
                                         }
                                     }
                                     //插入动态消息
                                     sqls.push(sql.news.insert);
                                     params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                 }
                                 msqlQueries.queries(sqls, params, function (err, result) {
                                     connection.release();
                                 });
                             }
                             else {
                                 connection.release();
                             }
                         }
                     });
                 });
             });
         });
     },
     confirm:function (req, res, next) {
         if (util.isParameterEmpty(req.body.user_id, req.body.issue_id)){
             res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
             return;
         }
         if (!util.isValidSession(req, 'PUT')) {
             res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
             return;
         }
         mysqlPool.connection(function (err, connection) {
             if (err) {
                 throw err;
             }
             var issue = null;
             var task = null;
             new Promise(function (resolve) {
                 connection.query(sql.issue.findIssue, [req.body.issue_id], function (err, result) {
                     if (err) {
                         res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '确认问题失败'));
                         connection.release();
                     } else {
                         if (result.length > 0){
                             resolve(result[0]);
                         } else {
                             res.json(util.toJson(code.NOT_EXISTED, '问题不存在，无法确认'));
                             connection.release();
                         }
                     }
                 });
             }).then(function (result) {
                 //问题创建者或看板管理员可以确认问题
                 return new Promise(function (resolve) {
                     issue = result;
                     connection.query(sql.task.findOne, [issue.task_id], function (err, results) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '确认问题失败'));
                             connection.release();
                         } else {
                             if (results.length > 0){
                                resolve(results[0]);
                             } else {
                                 res.json(util.toJson(code.NOT_EXISTED, '问题所归属的任务不存在，无法确认'));
                                 connection.release();
                             }
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     task = result;
                     connection.query(sql.board.findBoardDetail, [task.board_id], function (err, result) {
                        if (err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '确认问题失败'));
                            connection.release();
                        } else {
                            if(result.length > 0) {
                                var board = result[0];
                                if(req.body.user_id === board.creator ||
                                    req.body.user_id === issue.creator){
                                    //问题的创建者或看板的管理员才可以确认问题
                                    resolve(issue);
                                } else {
                                    res.json(util.toJson(code.IS_NOT_CAN, '您不是问题的创建者或者看板管理员，无法确认问题'));
                                    connection.release();
                                }
                            } else {
                                res.json(util.toJson(code.NOT_EXISTED, '问题所属的看板不存在，无法确认问题'));
                                connection.release();
                            }
                        }
                    });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     var issue = result;
                     if (issue.current_status === 1){
                         //只有状态为1（已完成）时可以确认
                         resolve(issue);
                     } else {
                         res.json(util.toJson(code.IS_NOT_CAN, '问题的状态不对，无法确认'));
                         connection.release();
                     }
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     connection.query(sql.issue.updateStatus, [2, req.body.issue_id], function (err, result) {
                         if(err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '问题确认失败'));
                             connection.release();
                         } else {
                             res.json(util.toJson(code.OPERATE_SUCCESS, '问题确认成功'));
                             // connection.release();
                             resolve();
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     connection.query(sql.board.findBoardMembersAll, [task.board_id], function (err, results) {
                         if (err) {
                             connection.release();
                         } else {
                             if(results.length > 0) {
                                 var index = 0;
                                 //查找当前操作者
                                 for (var i = 0; i < results.length; i++){
                                     if (results[i].user_id === req.body.user_id){
                                         index = i;
                                         break;
                                     }
                                 }
                                 var content = results[index].user_name + '在任务：' + task.task_content + '里确认了一个问题';
                                 var params = [];
                                 var sqls = [];
                                 for (var j = 0; j < results.length; j++) {
                                     if (results[j].user_id !== req.body.user_id) {
                                         if (!util.isParameterEmpty(results[j].client_id)) {
                                             getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                 console.log(data);
                                             },function (err) {
                                                 console.error(err);
                                             });
                                         }
                                     }
                                     //插入动态消息
                                     sqls.push(sql.news.insert);
                                     params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                 }
                                 msqlQueries.queries(sqls, params, function (err, result) {
                                     connection.release();
                                 });
                             }
                             else {
                                 connection.release();
                             }
                         }
                     });
                 });
             });
         });
     },
     rollback:function (req, res, next) {
         if (util.isParameterEmpty(req.body.user_id, req.body.issue_id)){
             res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
             return;
         }
         if (!util.isValidSession(req, 'PUT')) {
             res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
             return;
         }
         mysqlPool.connection(function (err, connection) {
             if (err) {
                 throw err;
             }
             var issue = null;
             var task = null;
             new Promise(function (resolve) {
                 connection.query(sql.issue.findIssue, [req.body.issue_id], function (err, result) {
                     if (err) {
                         res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '打回问题失败'));
                         connection.release();
                     } else {
                         if (result.length > 0){
                             resolve(result[0]);
                         } else {
                             res.json(util.toJson(code.NOT_EXISTED, '问题不存在，无法打回'));
                             connection.release();
                         }
                     }
                 });
             }).then(function (result) {
                 //问题创建者或看板管理员可以打回问题
                 return new Promise(function (resolve) {
                     issue = result;
                     connection.query(sql.task.findOne, [issue.task_id], function (err, results) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '打回问题失败'));
                             connection.release();
                         } else {
                             if (results.length > 0){
                                 resolve(results[0]);
                             } else {
                                 res.json(util.toJson(code.NOT_EXISTED, '问题所归属的任务不存在，无法打回'));
                                 connection.release();
                             }
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     task = result;
                     connection.query(sql.board.findBoardDetail, [task.board_id], function (err, result) {
                         if (err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '打回问题失败'));
                             connection.release();
                         } else {
                             if(result.length > 0) {
                                 var board = result[0];
                                 if(req.body.user_id === board.creator ||
                                     req.body.user_id === issue.creator){
                                     //问题的创建者或看板的管理员才可以打回问题
                                     resolve(issue);
                                 } else {
                                     res.json(util.toJson(code.IS_NOT_CAN, '您不是问题的创建者或者看板管理员，无法打回问题'));
                                     connection.release();
                                 }
                             } else {
                                 res.json(util.toJson(code.NOT_EXISTED, '问题所属的看板不存在，无法打回问题'));
                                 connection.release();
                             }
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     var issue = result;
                     if (issue.current_status === 1){
                         //只有状态为1（已完成）时可以打回
                         resolve(issue);
                     } else {
                         res.json(util.toJson(code.IS_NOT_CAN, '问题的状态不对，无法打回'));
                         connection.release();
                     }
                 });
             }).then(function (result) {
                 return new Promise(function (resolve) {
                     connection.query(sql.issue.updateStatus, [3, req.body.issue_id], function (err, result) {
                         if(err) {
                             res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '问题打回失败'));
                             connection.release();
                         } else {
                             res.json(util.toJson(code.OPERATE_SUCCESS, '问题打回成功'));
                             // connection.release();
                             resolve();
                         }
                     });
                 });
             }).then(function (result) {
                 return new Promise(function (resovle) {
                     connection.query(sql.board.findBoardMembersAll, [task.board_id], function (err, results) {
                         if (err) {
                             connection.release();
                         } else {
                             if(results.length > 0) {
                                 var index = 0;
                                 //查找当前操作者
                                 for (var i = 0; i < results.length; i++){
                                     if (results[i].user_id === req.body.user_id){
                                         index = i;
                                         break;
                                     }
                                 }
                                 var content = results[index].user_name + '在任务：' + task.task_content + '里打回了一个问题';
                                 var params = [];
                                 var sqls = [];
                                 for (var j = 0; j < results.length; j++) {
                                     if (results[j].user_id !== req.body.user_id) {
                                         if (!util.isParameterEmpty(results[j].client_id)) {
                                             getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                 console.log(data);
                                             },function (err) {
                                                 console.error(err);
                                             });
                                         }
                                     }
                                     //插入动态消息
                                     sqls.push(sql.news.insert);
                                     params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                 }
                                 msqlQueries.queries(sqls, params, function (err, result) {
                                     connection.release();
                                 });
                             }
                             else {
                                 connection.release();
                             }
                         }
                     });
                 });
             });
         });
     }
};